import axios, { Axios, AxiosRequestConfig, AxiosResponse } from 'axios';
import { useAuthStoreWithOut } from '@/store/module/useAuthStore';

export class Request {
  private instance: Axios;
  constructor(props: AxiosRequestConfig, useInterceptors = true) {
    // 使用拦截器
    this.instance = axios.create(props);
    if (useInterceptors) {
      this.initInterceptors();
    }
  }
  initInterceptors() {
    this.instance.interceptors.request.use(this.useRequestOnFulfilled(), this.useRequestOnReject());
    this.instance.interceptors.response.use(
      this.useResponseOnFulfilled(),
      this.useResponseOnReject()
    );
  }
  request<T = any, R = AxiosResponse<T>, D = any>(props: AxiosRequestConfig<D>): Promise<R> {
    return this.instance.request(props);
  }
  useRequestOnFulfilled() {
    return (config: AxiosRequestConfig): AxiosRequestConfig => {
      // header[authorization] = bearer token
      const authStore = useAuthStoreWithOut();
      config!.headers = config.headers || {};
      config!.headers['Authorization'] = authStore.getToken || '';
      return config;
    };
  }
  useResponseOnFulfilled() {
    return (response: AxiosResponse): Promise<any> => {
      return Promise.resolve(response);
    };
  }
  useRequestOnReject() {
    return (error: any): Promise<any> => {
      return Promise.reject(error);
    };
  }
  useResponseOnReject() {
    return (error: any): Promise<any> => {
      return Promise.reject(error);
    };
  }
}

export const userHttp = new Request({
  baseURL: import.meta.env.VITE_USER_API_URL,
  timeout: 3000,
});

export const dataShowHttp = new Request({
  baseURL: import.meta.env.VITE_DATASHOW_API_URL,
  timeout: 3000,
});

export const earlyWarningHttp = new Request({
  baseURL: import.meta.env.VITE_EARLYWARNING_API_URL,
  timeout: 10000,
});
